package com.quasar.hpatient.module.comm_regist;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.mob.MobSDK;
import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.comm_regist.RegistBean;

import java.util.HashMap;
import java.util.regex.Pattern;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelAcceptChangeListener;
import lib.quasar.context.BaseApp;
import lib.quasar.context.BaseConstant;
import lib.quasar.widget.timer.TimerView;
import okhttp3.RequestBody;

/**
 * description: 用户注册
 * created by kalu on 2018/3/22 16:57
 */
public class RegistPresenter implements BasePresenter {

    @SuppressLint("CheckResult")
    void sendCode(final RegistView view, TextView phone, TextView code, TimerView timer, View button) {

        if (null == view || null == code || null == phone || null == timer || null == button)
            return;

        final String number = phone.getText().toString().trim();
        if (TextUtils.isEmpty(number)) {
            view.warning("手机号码为空");
            return;
        }

        final Pattern compile1 = Pattern.compile("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$");
        if (!compile1.matcher(number).matches()) {
            view.warning("请输入正确手机号");
            return;
        }

        Observable.create((ObservableOnSubscribe<Boolean>) e -> {

            MobSDK.init(BaseApp.getContext(), BaseConstant.MOB_NAME, BaseConstant.MOB_ID);
            SMSSDK.registerEventHandler(new EventHandler() {
                public void afterEvent(int event, int result, Object data) {
                    SMSSDK.unregisterAllEventHandler();
                    e.onNext(result == SMSSDK.RESULT_COMPLETE);
                }
            });
            // 触发操作
            SMSSDK.getVerificationCode(BaseConstant.MOB_PHONE, number);

        }).subscribeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> {

                    view.toast(aBoolean ? "发送验证码成功" : "发送验证码失败");
                    if (aBoolean) {

                        view.setVisibility(button, aBoolean ? View.GONE : View.VISIBLE);
                        view.setVisibility(timer, aBoolean ? View.VISIBLE : View.GONE);
                        phone.clearFocus();
                        code.requestFocus();

                        timer.setOnCountdownChangeListener(() -> {
                            view.setVisibility(button, aBoolean ? View.VISIBLE : View.GONE);
                            view.setVisibility(timer, aBoolean ? View.GONE : View.VISIBLE);
                        });
                        timer.startTimer();
                    }
                });
    }

    @SuppressLint("CheckResult")
    void pushCode(final RegistView view, TextView phone, TextView code) {

        if (null == view || null == phone || null == code) return;

        final String number = phone.getText().toString().trim();
        if (TextUtils.isEmpty(number)) {
            view.warning("手机号码为空");
            return;
        }

        if (!phone.isEnabled()) {
            view.codeSucc();
            return;
        }

        final String codes = code.getText().toString().trim();
        if (TextUtils.isEmpty(codes)) {
            view.warning("验证码为空");
            return;
        }

        Observable.create((ObservableOnSubscribe<Boolean>) e -> {

            MobSDK.init(BaseApp.getContext(), BaseConstant.MOB_NAME, BaseConstant.MOB_ID);
            SMSSDK.registerEventHandler(new EventHandler() {
                public void afterEvent(int event, int result, Object data) {
                    SMSSDK.unregisterAllEventHandler();
                    e.onNext(result == SMSSDK.RESULT_COMPLETE);
                }
            });
            // 触发操作
            SMSSDK.submitVerificationCode(BaseConstant.MOB_PHONE, number, codes);

        }).subscribeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> {
                    view.toast(aBoolean ? "验证码验证成功" : "验证码验证失败");
                    if (!aBoolean) return;
                    phone.setEnabled(false);
                    code.clearFocus();
                    view.codeSucc();
                });
    }

    void regist(final RegistView view, final TextView userId, TextView password1, TextView password2, boolean regist) {

        if (null == view || null == userId || null == password1 || null == password2) return;

        final String trim1 = userId.getText().toString().trim();
        if (TextUtils.isEmpty(trim1)) {
            view.warning("手机号不能为空");
            return;
        }

        final Pattern compile1 = Pattern.compile("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$");
        if (!compile1.matcher(trim1).matches()) {
            view.warning("请输入正确手机号");
            return;
        }

        final String trim2 = password1.getText().toString().trim();
        final String trim3 = password2.getText().toString().trim();
        if (TextUtils.isEmpty(trim2)) {
            view.warning("新密码不能为空");
            return;
        }

        final Pattern compile = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z_]{6,25}$");
        if (!compile.matcher(trim2).matches()) {
            view.warning("新密码由6-25位字母, 数字组成");
            return;
        }

        if (TextUtils.isEmpty(trim3)) {
            view.warning("二次验证密码不能为空");
            return;
        }

        if (TextUtils.isEmpty(trim2) || TextUtils.isEmpty(trim3) || !trim2.equals(trim3)) {
            view.warning("请输入密码");
            return;
        }

        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.PASSWORD, trim3);
        map.put(HttpParams.PHONE, trim1);
        map.put(HttpParams.USER_TYPE, BaseConstant.TWO);
        final RequestBody params = createParams(map, regist ? HttpParams.DATA_TYPE_1_1 : HttpParams.DATA_TYPE_1_12);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().regist(params);

        request(observable, new OnModelAcceptChangeListener<RegistBean>() {

            @Override
            public void modelStart() {
                view.beginLoading();
            }

            @Override
            public void modelComplete() {
                view.closeLoading();
            }

            @Override
            public void modelSucc(RegistBean model) {
                view.goCompile();
            }
        });
    }

    @Override
    public void recycler() {
    }
}
